#!/bin/sh
# 
# split initrd, codes are copied from: /usr/bin/unmkinitramfs
# 

itrd=$1
{ [ $# -gt 0 ] && [ -e "$1" ]; } || {
	echo "Please specify initrd file."
	echo ""
	echo "Usage: sh %0 <initrd>"
	echo "  Example:"
	echo "    sh $0 /cdrom/casper/initrd"
	exit 1
}

readhex()
{
	dd < "$1" bs=1 skip="$2" count="$3" status=none |
		LANG=C grep -E "^[0-9A-Fa-f]{$3}\$"
}

checkzero() {
	dd < "$1" bs=1 skip="$2" count=1 status=none |
		LANG=C grep -q -z "^$"
}

count=0; start=0
while true; do
	end=$start
	while true; do
		if checkzero "$itrd" $end; then
			end=$((end + 4))
			while checkzero "$itrd" $end; do
				end=$((end + 4))
			done
			break
		fi
		magic="$(readhex "$itrd" $end 6)" || break
		[ "$magic" = 070701 ] || [ "$magic" = 070702 ] || break
		namesize=0x$(readhex "$itrd" $((end + 94)) 8)
		filesize=0x$(readhex "$itrd" $((end + 54)) 8)
		end=$(((end + 110)))
		end=$(((end + namesize + 3) & ~3))
		end=$(((end + filesize + 3) & ~3))
	done
	[ $end -eq $start ] && break
	count=$((count + 1))
	echo "Early cpio $count, $start -- $end, magic=$magic, namesize=$namesize, filesize=$filesize."
	dd if="$itrd" skip=$start count=$((end - start)) iflag=skip_bytes,count_bytes status=none of=early.$count.cpio || exit $?
	file early.$count.cpio
	start=$end
done
if [ $end -gt 0 ]; then
	echo "Main cpio at $end."
	dd if="$itrd" skip=$end iflag=skip_bytes status=none of=main.cpio.xx || exit $?
	file main.cpio.xx
else
	echo "No early cpio found."
fi

